import csv
import os
from config.config import slow_api_path
from datetime import datetime

class ApiLogger:
    def __init__(self,filname=slow_api_path):
        self.filename = filname
        self.fieldnames = ["timestamp", "url", "method", "params", "data", "json", "response_time"]

        # 判断如果文件不存在或文件内容为空时，就写入表头
        if not os.path.exists(self.filename) or os.path.getsize(self.filename) == 0:
            with open(self.filename,'a',newline='') as file:
                writer = csv.DictWriter(file,fieldnames=self.fieldnames)
                writer.writeheader()

    def log_request(self,url,method,params,data,json,response_time):
        if response_time >=100:
            timstamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            request_data = {
                "timestamp":timstamp,
                "url":url,
                "method":method,
                "params":params,
                "data":data,
                "json":json,
                "response_time":response_time
            }

            with open(self.filename,'a',newline='') as file:
                writer = csv.DictWriter(file, fieldnames=self.fieldnames)
                writer.writerow(request_data)

